<template>
  <div class="header">
    <div class="header_container">
      <div class="header_container_left">
        <p>{{ currentTime }}</p>
        <p class="nav">
          <span
            class="hoverStyle"
            :style="computedStyle()"
            @click="$router.push('/')"
            >{{ $t("home") }}</span
          >
          |
          <span class="hoverStyle" @click="toLink">WhatsApp</span>
        </p>
      </div>
      <div class="header_container_right">
        <div v-if="isLogin" class="userInfo">
          <p>{{ $t("ID") }}: {{ uid }}</p>
          <p>
            {{ $t("balance") }}:
            <span style="color: #f2ce43">
              {{ isLogin ? formatMoney(total_balance, true) : "--" }}</span
            >
            USDT
          </p>
          <p class="refresh" @click="refresh">{{ $t("refresh") }}</p>
          <p class="hoverStyle" @click="toAccount">{{ $t("MemberCenter") }}</p>
          <p class="hoverStyle" @click="toMessage">
            {{ $t("Message") }}
          </p>
        </div>
        <div v-if="!isLogin" class="inputSearch">
          <el-input v-model="email" :placeholder="$t('username')"></el-input>
          <el-input
            v-model="password"
            :placeholder="$t('password')"
            type="password"
          ></el-input>
        </div>
        <p class="loginBtn" @click="logOpera">
          {{ isLogin ? $t("logOut") : $t("logIn") }}
        </p>
        <p
          class="registerBtn"
          v-if="!isLogin"
          @click="$router.push('/register')"
        >
          {{ $t("register") }}
        </p>
        <el-dropdown trigger="click" @command="handleCommand">
          <div class="langBox">
            <img src="@/assets/img/language.png" alt="" class="langImg" />
            <span>{{ currentLan }}</span>
          </div>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item
              v-for="(lang, index) in langs"
              :key="index"
              :command="lang"
              >{{ lang.text }}</el-dropdown-item
            >
          </el-dropdown-menu>
        </el-dropdown>
      </div>
    </div>
  </div>
</template>
<script>
import { httpInfo, httpWalletBalance, httpMobileLogin } from "@/http/api";
import { formatMoney } from "@/utils/common";
export default {
  name: "Header",
  data() {
    return {
      currentTime: "", // 存储当前时间的变量
      total_balance: 0,
      gold: 0,
      uid: "",
      currentPath: "",
      isLogin: localStorage.getItem("TOKEN") ? true : false,
      langs: [
        { text: "English", value: "en" },
        { text: "ภาษาไทย", value: "th" },
      ],
      curLanguage: localStorage.getItem("accept_language"),
      currentLan: "",
      timer: null,
      loginAjax: false,
      email: "",
      password: "",
    };
  },
  computed: {
    computedStyle() {
      return () => {
        if (this.$route.path == "/") {
          return {
            color: "#f2ce43",
          };
        }
      };
    },
    // computedStyle() {
    // if (this.$route.path == "/") {
    //   return {
    //     color: this.textColor,
    //   };
    // }
    // },
  },
  created() {
    this.currentLan = this.langs.find(
      (item) => item.value === this.curLanguage
    )?.text;
    this.getHttpInfo();
    this.getHttpGameBalance();
    this.currentPath = this.$route.path;
  },
  beforeDestroy() {
    // 在组件销毁前清除计时器，避免内存泄漏
    clearInterval(this.timer);
  },
  methods: {
    toLink() {
      window.open("https://api.whatsapp.com/send?phone=12133974557");
    },
    formatMoney,

    refresh() {
      this.$router.push("/");
      location.reload();
    },
    updateCurrentTime() {
      const now = new Date();
      const year = now.getFullYear();
      const month = this.padZero(now.getMonth() + 1);
      const day = this.padZero(now.getDate());
      const hours = this.padZero(now.getHours());
      const minutes = this.padZero(now.getMinutes());
      const seconds = this.padZero(now.getSeconds());

      // 更新当前日期时间
      this.currentTime = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
    },
    padZero(value) {
      return value < 10 ? "0" + value : value;
    },
    logOpera() {
      if (!this.isLogin) {
        this.login();
      } else {
        localStorage.clear();
        this.isLogin = false;
        if (this.$route.path == "/") {
          location.reload();
        } else {
          this.$router.replace("/");
        }
      }
    },
    goToRegisterPage() {
      // 获取浏览器 URL 中的 invited_code 参数
      const urlParams = new URLSearchParams(window.location.search);
      const invitedCode = urlParams.get("invite_code");
      //console.log("invitedCode:", invitedCode);
      // 构建 register 页面的路径，并将 invited_code 作为参数传递
      const registerPath = {
        path: "/register",
        query: { invite_code: invitedCode },
      };

      // 使用 $router.push 导航到 register 页面
      this.$router.push(registerPath);
    },
    handleCommand(command) {
      localStorage.setItem("accept_language", command.value);
      this.$i18n.locale = command.value;
      this.currentLan = this.langs.find(
        (item) => item.value === command.value
      )?.text;
      window.location.reload();
    },

    // 获取用户信息
    async getHttpInfo() {
      let res = await httpInfo();
      if (res.code == 0) {
        this.uid = res.data?.uid || "";
      }
    },
    // 余额
    // httpGameBalance
    async getHttpGameBalance() {
      let res = await httpWalletBalance();
      if (res.code === 0) {
        this.gold = res.data?.gold || 0;
        this.total_balance = res.data?.total_balance || 0;
        // this.gethttpWalletBalance();
      }
    },
    // login
    async login() {
      if (this.loginAjax) return;
      if (!this.email) return;
      if (!this.password.trim()) return;

      let params = {
        account_name: this.email,
        password: this.password,
        type: "email",
      };

      let res = await httpMobileLogin(params);
      if (res.code == 0) {
        this.$message({
          type: "success",
          message: "登录成功",
        });
        if (res.code == 0) {
          localStorage.setItem("TOKEN", res.data.token);
          // 获取用户信息
          let res2 = await httpInfo();
          if (res2.code == 0) {
            localStorage.setItem("email", this.email.trim());
            localStorage.setItem("mobile", this.mobile);
            localStorage.setItem("areaCode", this.areaCode);
            localStorage.setItem("account_name", res2.data.account_name);
            localStorage.setItem("invite_code", res2.data.invite_code);
            localStorage.setItem("uid", res2.data.uid);
            localStorage.setItem("avatar", res2.data.avatar);
            localStorage.setItem("is_agent", res2.data.is_agent);
            localStorage.setItem(
              "accept_language",
              res2.data["accept-language"] || "en"
            );
            this.isLogin = true;
          }
        }
      } else {
        this.$message.error(res.message);
      }
      this.loginAjax = false;
    },
    toMessage() {
      this.$router.push({ name: "message" });
      this.$emit("message");
    },
    toAccount() {
      this.$router.push({ name: "exchange" });
      this.$emit("toAccount");
    },
  },
  mounted() {
    // 页面加载完成后立即更新当前时间
    this.updateCurrentTime();
    // 每秒更新一次当前时间
    this.timer = setInterval(this.updateCurrentTime, 1000);
  },
};
</script>
<style lang="less" scoped>
.header {
  background: #472d18;
  display: flex;
  justify-content: center;
  align-items: center;
  .header_container {
    width: 1200px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .header_container_left {
      display: flex;
      align-items: center;
      font-size: 16px;
      p {
        width: 170px;
        // margin-right: 10px;
        color: #fff !important;
      }
      .nav {
        span {
          color: #fff;
          cursor: pointer;
        }
      }
      .hoverStyle {
        &:hover {
          color: #eaf400;
          cursor: pointer;
        }
      }
    }
    .header_container_right {
      display: flex;
      color: #fff !important;
      align-items: center;
      font-size: 16px;
      .userInfo {
        display: flex;
        justify-content: center;
        align-items: center;
      }
      span {
        color: #fff;
      }
      p {
        margin-right: 10px;
        color: #fff !important;
      }
      .refresh {
        background: #eaf400;
        color: #5d3100 !important;
        border-radius: 5px;
        padding: 0 5px;
        cursor: pointer;
        line-height: 24px;
      }
      .loginBtn {
        background: #eaf400;
        color: #5d3100 !important;
        border-radius: 5px;
        padding: 0 5px;
        cursor: pointer;
        line-height: 24px;
      }
      .registerBtn {
        background: #ec6941;
        color: #fff !important;
        border-radius: 5px;
        padding: 0 5px;
        cursor: pointer;
        line-height: 24px;
      }
      .langBox {
        display: flex;
        justify-content: center;
        align-items: center;
        .langImg {
          width: 15px;
          height: 15px;
          margin-right: 3px;
        }
      }
    }
    .hoverStyle {
      &:hover {
        color: #eaf400 !important;
        cursor: pointer;
      }
    }
  }
}
</style>
